package com.centerm.bluetooth.ibridge;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

final class BluetoothIBridgeDeviceFactory {
	/**
	 * Singleton
	 */
	private static BluetoothIBridgeDeviceFactory INSTANCE = null;
	private static byte[] LOCK = new byte[0];
	private List<BluetoothIBridgeDevice> mList;

	// prevent instantiation outside
	private BluetoothIBridgeDeviceFactory() {
		mList = new ArrayList<BluetoothIBridgeDevice>();
	}

	public static BluetoothIBridgeDeviceFactory getDefaultFactory() {
		synchronized (LOCK) {
			if (INSTANCE == null) {
				INSTANCE = new BluetoothIBridgeDeviceFactory();
			}
		}
		return INSTANCE;
	}

	public synchronized BluetoothIBridgeDevice createDevice(BluetoothDevice device) {
		if (null != device) {
			Iterator<BluetoothIBridgeDevice> it = mList.iterator();
			while (it.hasNext()) {
				BluetoothIBridgeDevice idev = it.next();
				if (idev != null && idev.isSameDevice(device)) {
					return idev;
				}
			}
			BluetoothIBridgeDevice newDev = new BluetoothIBridgeDevice(device);
			mList.add(newDev);//��������豸
			return newDev;
		}
		return null;
	}

	public synchronized BluetoothIBridgeDevice createDevice(String address) {
		BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
		if (adapter != null) {
			return createDevice(adapter.getRemoteDevice(address));
		}
		return null;
	}
}
